<template>
  <div class="courseDetail">
    <div class="course-header">
      <div class="header-content">
        <div class="courseDesc">
          <breadcrumb class="hidden-xs-only" />
          <div class="courseName">
            {{ courseInfo.currName || courseInfo.name || "课程名" }} <span style="font-size: 20px;">({{ "已选" +
              (courseInfo.choosedNum || 0) + "人" }})</span>
          </div>
          <div class="descDetail">
            <div class="teacher-detail">
              <div class="picture">
                <img v-lazy="courseInfo.tutorStaffIconPath" alt="" />
              </div>
              <div class="teacherDesc">
                <div class="name">
                  {{ courseInfo.tutorStaffUserName || "教师名称" }}
                </div>
                <div class="label">教师</div>
              </div>
            </div>
            <!-- <div class="viewScore" v-if="$route && $route.name == 'Curr'">
              <span @click="openViewScore">课程成绩</span>
            </div> -->
            <el-button type="primary" size="large" style="font-size: 16px;" @click="openViewScore(false)"
              v-if="$route && $route.name == 'Curr'">课程成绩</el-button>
            <el-button type="warning" size="large" style="font-size: 16px;" @click="openViewScore(true)"
              v-if="userInfo.userID && $route && $route.name == 'Curr'">我的成绩</el-button>

            <el-button type="danger" size="large" disabled v-if="courseInfo.state == '已结课'">本课程已结束</el-button>
            <el-button type="danger" size="large" style="font-size: 16px;" @click.stop="endCourse"
              v-else-if="userInfo.userID == 226">结课</el-button>
          </div>
        </div>
        <!-- <div class="courseShare-box hidden-xs-only">
          <share />
        </div> -->
      </div>
    </div>
    <div class="course-headerNav">
      <div class="headerNav-content">
        <ul>
          <li v-for="(value, key) in pages" :key="key" :class="getActiveName == key ? 'li-active' : ''"
            @click="activeName = key">
            {{ value }}
            <div class="liBadge" v-if="key == 'Question'">{{ questionCount }}</div>
          </li>
        </ul>
      </div>
    </div>
    <div class="course-main">
      <div class="finishSituation" :class="{ isSelected: myStudyData.length }">
        <div v-for="(item, index) in courseInfo.content" :key="index" class="situationIconBox"
          :class="{ isFinish: item.state == taskState['studied'] }" @click="scrollIntoView(index)">
          <div class="IconBox">
            <img src="../../../assets/images/taskUnfinish2.png"
              v-if="item.state == taskState['unstudy'] || !myStudyData.length" />
            <img src="../../../assets/images/taskLearning2.png" class="tNfinishIcon"
              v-if="item.state == taskState['studying']" />
            <img src="../../../assets/images/taskFinish2.png" class="tNfinishIcon"
              v-if="item.state == taskState['studied']" />
          </div>
          <div class="name">
            {{ item.name }}
          </div>
        </div>
      </div>
      <!-- 插槽 -->
      <div class="mall-studyAndstudent studyAndstudent">
        <div class="studyBox">
          <div class="courseName" :title="courseInfo.currName || courseInfo.name || '课程名'">
            {{ courseInfo.currName || courseInfo.name || "课程名" }}
          </div>
          <div class="selectedCourse">
            <div class="desc">
              <div class="percent">难度：<em>{{ courseInfo.taskTotal > 20 ? "中等" : courseInfo.taskTotal > 35 ? "困难" :
                "简单" }}</em> | 时长：约<em>{{ (courseInfo.taskTotal * 2) || 0 }}</em>小时</div>
            </div>
            <div class="speedOfProgress"><span>任务数：<em>{{ courseInfo.taskTotal || 0 }}</em></span> <span>学习人数：<em>{{
              courseInfo.choosedCount || 0 }}</em></span></div>
            <div class="price">
              <span class="newPrice">￥{{ courseInfo.taskTotal * 5 }}</span>
              <span class="oldPrice">原价￥{{ courseInfo.taskTotal * 6 }}</span>
            </div>
          </div>
          <button class="btn" @click="buy">
            立即购买
          </button>
        </div>
      </div>
      <div class="studyAndstudent"
        v-if="getActiveName == 'Task' && ((courseInfo.courseType == '比赛' && !isChoose) || courseInfo.courseType !== '比赛')">
        <div class="studyBox">
          <div class="selectedCourse" v-if="myStudyData.length && courseInfo.courseType !== '比赛'">
            <div class="desc">
              <div class="percent">已学 {{ computedLearned }} %</div>
            </div>
            <div class="progress">
              <el-progress :percentage="computedLearned" color="#f6ad35" :show-text="false" :stroke-width="16" />
            </div>
            <div class="speedOfProgress">{{ speedOfProgress }}</div>
          </div>
          <!-- <div :class="{'ischeckTeachered': courseInfo.shouldChooseTutor}"> -->
          <el-popover placement="bottom-start" :width="userInfo.accessToken ? '1050' : '300'"
            v-model="visibleSelectTeacher" v-if="courseInfo.shouldChooseTutor" @after-leave="closeSelectTeacher"
            popper-class="selectTeacher" @show="handleChangeShowProper">
            <div v-if="userInfo.accessToken">
              <p style="margin-bottom:5px;">请选择本课程的指导老师</p>
              <div style="margin-bottom:5px;" v-if="!filterTutorList.length">
                未找到可指定教师，请检查个人中心是否未绑定班级。
              </div>
              <el-radio-group v-model="checkTeacher">
                <div class="teacherBox" v-for="(Titem, Tindex) in filterTutorList" :key="Tindex"
                  :class="{ isSelectTeacher: checkTeacher == Titem.userID }">
                  <div class="imgBox"><img v-lazy="filterIconPath(Titem)" v-if="Titem && Titem.iconPath"></div>
                  <div>
                    <div class="teacherInfo">
                      <p class="teacherName">教师：{{ filterName(Titem) }}</p>
                      <div class="teacherDesc">
                        <el-tooltip class="item" popper-class="teacherDescToolTip" effect="dark"
                          :content="Titem.userDesc" placement="top-end">
                          <span>简介：{{ Titem.userDesc || '无' }}</span>
                        </el-tooltip>
                      </div>
                    </div>
                    <el-radio :label="Titem.userID" style="min-width: 480px;">选择</el-radio>
                    <span>已选人数：{{ Titem.selectedStuCount }}</span>
                  </div>
                </div>
              </el-radio-group>
            </div>
            <p v-else>请登录后再操作!</p>
            <!-- otherTutorUserIDList -->
            <div style="text-align: right; margin: 0; margin-top: 5px;" v-if="userInfo.accessToken">
              <el-button size="mini" type="text" @click="closeSelectTeacher">取消</el-button>
              <el-button type="primary" size="mini" v-if="!isChoose"
                :disabled="!checkTeacher || !filterTutorList.length"
                @click="chooseCourse(checkTeacher), (visibleSelectTeacher = false)">确定</el-button>
              <el-button type="primary" size="mini" v-else :disabled="!checkTeacher || !filterTutorList.length"
                @click="chooseUpdate(checkTeacher), (visibleSelectTeacher = false)">确定</el-button>
            </div>
            <button v-if="!isChoose" class="btn" id="startStudy" slot="reference">{{ courseInfo.courseType == '比赛' ?
              '报名参赛' : '开始学习' }}</button>
            <div v-else class="chooseTeacher" slot="reference">{{ '指导老师：' + `${selectedTutorName || '未选指导老师'}` }} <span
                style="margin-left: 10px;">修改</span></div>
          </el-popover>
          <button class="btn" id="startStudy" @click="chooseCourse(null)" v-loading="!courseInfo.currNo"
            :disabled="!courseInfo.currNo" v-else-if="!isChoose">
            <!-- v-if="!isChoose && (!courseInfo.shouldChooseTutor && courseInfo.courseType !== '比赛')" -->
            {{ courseInfo.courseType == '比赛' ? '报名参赛' : '开始学习' }}
          </button>
          <button class="btn" id="continueStudy" v-if="isChoose && courseInfo.courseType !== '比赛'"
            @click="continueLearn">
            {{ courseInfo.courseType !== '比赛' ? '继续学习' : '跳转至任务' }}
          </button>
          <!-- </div> -->
          <div class="contentBox" v-if="!isChoose && courseInfo.courseType !== '比赛'">
            <div class="content">
              <div class="title">您还未选课学习，快来和我们一起学习吧！</div>
            </div>
          </div>
        </div>
      </div>
      <div class="danmuComponent" v-if="getActiveName == 'Task' && $route.name == 'Curr'">
        <ChooseTeacher :courseInfo="courseInfo" v-if="isTutorTeacher" />
        <DanMu :currNo="currNo" />
      </div>
      <task ref="rv" :courseInfo="courseInfo" :isGroupLeader="isGroupLeader" :myStudyData="myStudyData"
        :chooseNo="chooseNo" :isChoose="isChoose" :learnGroupIndex="learnGroupIndex" :checkTeacher="checkTeacher"
        :selectedTutorName="selectedTutorName" @handleChangeLSion="handleChangeLSion"
        @handleChangeProgress="handleChangeProgress" :successGetStudyData="successGetStudyData"
        v-if="getActiveName == 'Task'" />
      <question :courseInfo="courseInfo" :replyList="replyList" :currNo="currNo" :chooseNo="chooseNo"
        v-if="getActiveName == 'Question'" />
      <Progress v-if="getActiveName == 'Progress' && courseInfo.courseType !== '比赛'" :tableData="tableData"
        :courseInfo="courseInfo" :currNo="currNo" :courseID="courseID" />
      <div style="margin-top:20px;" v-if="getActiveName == 'Progress' && courseInfo.courseType == '比赛'">暂无比赛进度排行</div>
      <vote v-if="getActiveName == 'Vote'" :currNo="currNo" />
      <!-- :taskSettings="taskSettings" -->
    </div>
  </div>
</template>

<script>
const breadcrumb = () => import("@/components/Breadcrumb/index");
// const share = () => import("@/components/Share/index");
const task = () => import('@/views/courses/detail/task_N/task_N')
const question = () => import('@/views/courses/detail/question/question')
const Progress = () => import('@/views/courses/detail/progress/progress')
const vote = () => import('@/views/courses/detail/vote/vote')
const DanMu = () => import('@/components/DanMu/danmuMessage')
const ChooseTeacher = () => import('./chooseTeacher/index.vue')
import { taskState } from "@/util/guidingtextType";
import {
  getCourseDetail,
  getSingleChooseInfo,
  getChooseCreate,
  getChooselist,
  getCurriculumCourse,
  getMyStudyData,
  getChooseUpdateTutor,
} from "@/request/courses";
// import {getChooseNoData} from '@/request/teacher'
import { mapState } from "vuex";
import {
  handleChangeTaskCommitJsonToArray,
  formatCourseGroupTaskObj,
} from "@/util/courseData";
import { toMs, isJSONstr, changeSubmitContentfomart, location_QuestionBank } from "@/util/tool";
import { getQuestionList } from "@/request/qAnswer"
import { getCurrNoData_Stu } from "@/request/teacher";
// import { getMyChoose } from "@/request/courses"
import { Session } from "@/util/storage/session"
import { getNewGuidelineStudyData } from "@/util/mockTaskData.js"
import { notification } from "ant-design-vue";
import { Notification } from "element-ui";
// import { b } from "@/util/testCourseInfo";
// import { a } from "@/util/testCourseData";
export default {
  name: "Curr",
  components: {
    breadcrumb,
    // share,
    task,
    question,
    Progress,
    vote,
    DanMu,
    ChooseTeacher
  },
  data() {
    return {
      taskState,
      activeName: "Task",
      pages: {
        Task: "任务",
        Question: "问答",
        Progress: "进度榜",
        Vote: "投票榜"
      },
      courseInfo: {
        name: "",
      },
      myStudyData: [], // 我的学习数据 新
      currCourseInfo: {},
      chooseNo: null,
      isGroupLeader: false,
      learnGroupIndex: "0-0", // 在学习的任务组 默认0
      lastLearn: null,
      speedOfProgress: "任务学习情况",
      computedLearned: 0,
      showRouteView: true,
      replyList: [],
      visibleSelectTeacher: false,
      checkTeacher: "", // 选择指导老师
      tableData: [], // 排行榜数据
      currNo: null,
      courseID: null,
      selectedTutorName: '',
      successGetStudyData: true,
      // taskSettings: null,
    };
  },
  watch: {
    // "$route.query"(n, o) {
    // if (n?.courseId && n?.currNo) this.handleCourseDetailCreate();
    // this.showRouteView = false;
    // this.$nextTick(() => {
    //   this.showRouteView = false;
    // });
    // },
    userInfo(n) {
      if (this.userInfo.accessToken) {
        if (!this.tableData.length) this.fetchCurrNoData({ currNo: Number(this.currNo) });
        if (!this.replyList.length) this.fetchQuestionInfo()
        if (!this.myStudyData.length) this.handleCourseDetailCreate();
      } else {
        this.myStudyData = []
        this.currCourseInfo = {}
        this.fetchLocalStorage().then((res) => {
          this.courseInfo = res.data;
        });
      }
    }
  },
  computed: {
    getActiveName() {
      return this.activeName;
    },
    ...mapState({
      userInfo: (state) => state.user.userInfo,
      getChooseCourses: function (state) {
        return state.courses.chooseCourses;
      },
    }),
    isChoose() {
      /**
       * 这里的currNo不能使用$roure.query的参数
       * 此页面使用了keep-alive 
       * 如果使用$route.query.currNo，切换了其它含有currNo参数的页面会影响此处的判断
       */
      let currNo = this.courseInfo.currNo
      // todo Es6 find() -> return findData === undefinde
      for (let i = 0; i < this.getChooseCourses.length; i++) {
        if (this.getChooseCourses[i].currNo == currNo) {
          return true;
        }
      }
      return false;
    },
    getCourseInfo() {
      // 课程信息还没读取到时 学习数据已经进入逻辑 返回一个假数据
      if (!this.courseInfo.content) {
        return {
          content: [],
        };
      }
      return this.courseInfo;
    },
    questionCount() {
      return this.replyList.length || ''
    },
    // 获取其它任课老师的信息
    getOtherTutorList() {
      let oList = this.courseInfo?.otherTutorUserIDList?.split(",") || []
      return this.courseInfo?.tutorList?.filter(item => {
        return oList.indexOf(`${item.userID}`) != -1
      })
    },
    filterName() {
      return function (data) {
        return data.realName || data.nickName || data.email || data.regName;
      };
    },
    filterIconPath() {
      return function (data) {
        return data.iconPath || '';
      };
    },
    // 过滤指定班级的教师
    filterTutorList() {
      let arr = []
      this.courseInfo.tutorMapJson.filter(item => {
        let t = this.courseInfo?.tutorList?.find(f => f.userID == item.tutorID)
        if (!item.classIDs.length) arr.push()
        if (item.classIDs.includes(this.userInfo.classID)) {
          return t && arr.push(t)
        }
        if (this.userInfo.otherClassIDList) {
          this.userInfo.otherClassIDList.split(',').map(i => Number(i)).forEach(oitem => {
            if (item.classIDs.includes(oitem)) {
              t && arr.push(t)
            }
          })
        }
      })
      return arr
    },
    isTutorTeacher() {
      return this.courseInfo.shouldChooseTutor && this.courseInfo?.tutorList?.find(item => item.userID == this.userInfo.userID)
    }
  },
  async created() {
    // this.fetchCourse();
    this.currNo = this.$route.params.id
    const { meta } = this.$route;
    // this.showRouteView = true;
    // 判断路由中是否含有courseId参数
    if (!this?.$route?.params?.id) {
      // this.$message({
      //   type: 'warning',
      //   message: '课程信息获取异常，正在跳转到课程列表页面',
      // })
      if (!this?.$router) return;
      this.$router.push({
        name: "CoursesList",
      });
    } else {
      // 判断是否登录 获取已选课程列表
      if (this.userInfo.accessToken) {
        this.fetchCurrNoData({ currNo: Number(this.currNo) });
        this.fetchQuestionInfo()
        this.handleCourseDetailCreate();
        // this.handleGetIsGroupLeader()
      } else {
        this.fetchLocalStorage().then((res) => {
          this.courseInfo = res.data;
          this.setTagsViewTitle({ name: this.courseInfo.currName, currNo: this.currNo });
        });
      }
    }
  },
  methods: {
    // 添加标签
    setTagsViewTitle(data) {
      if (this.$route.path === "/" || Number(data?.currNo) != Number(this.currNo)) return;
      const title = this.$route.meta.name;
      const courseName = data.name ? this.$route.name == "Curr" ? data.name : title : ` ${title}-${this.currNo}`;
      const route = Object.assign({}, this.$route, {
        title: courseName,
      });
      this.$store.dispatch("tagsView/updateVisitedView", route);
    },

    async endCourse() {

      this.$confirm(
        "结课后，本课程将进行归档，同时学生不能再学习本课程！！！确定吗？",
        {
          title: "重要提醒！！",
          confirmButtonText: "确定结课",
          cancelButtonText: "我再想想",
          type: "warning",
          callback: async (action) => {
            if (action == "confirm") {
              let params = {
                userID: this.userInfo.userID,
                currNo: this.currNo
              };
              const result = await this.$store.dispatch("courses/endCourse", { params: params })
            }
          },
        }
      );

    },
    // 锚点滚动
    scrollIntoView(index) {
      this.$nextTick(() => {
        document.getElementById("parentCollapse-" + index).scrollIntoView({
          behavior: "smooth",
        });
      });
    },

    // 获取已选课程
    async fetchChoosedCourses(params) {
      await getChooselist(params).then((data) => {
        if (data) {
          data.forEach((item) => {
            this.$set(item, "type", "学习");
            this.$set(item, "name", item.name.split("_")[0]);
          });
          this.$store.commit("courses/changeChooseCourses", data);
        }
      });
    },

    // 获取本地课程信息
    fetchLocalStorage() {
      return new Promise((resolve, reject) => {
        const currNo = this.currNo;
        // const courseID = this.courseID;
        const { meta } = this.$route;
        // 添加tagView标签
        this.setTagsViewTitle({ name: `${meta.name}-${currNo}`, currNo: this.currNo });

        let locals_CourseInfo = JSON.parse(localStorage.getItem("courseInfo"));
        if (!locals_CourseInfo) {
          locals_CourseInfo = [];
          this.fetchCoursesDeital().then((res) => {
            if (!res) return;
            resolve(res);
          });
        } else {
          let findCourseInfo = locals_CourseInfo.filter(
            (item) => item.currNo == currNo
          );
          if (findCourseInfo.length) {
            // 课程过期时间 普通课程10分钟缓存 持续发布课程30秒缓存
            if (
              (new Date().getTime() - findCourseInfo[0].saveTime > 600000 &&
                !findCourseInfo[0].isContinuousPublish) ||
              (new Date().getTime() - findCourseInfo[0].saveTime > 30000 &&
                findCourseInfo[0].isContinuousPublish)
            ) {
              this.fetchCoursesDeital().then((res) => {
                if (!res) return;
                resolve(res);
              });
            } else {
              // this.courseInfo = findCourseInfo[0];
              resolve({ data: findCourseInfo[0] });
            }
          } else {
            resolve(this.fetchCoursesDeital());
          }
        }
      });
    },

    // 获取课程详情 同时获取开设课程信息
    fetchCoursesDeital(params) {
      return new Promise((resolve, reject) => {
        // const getCourseDetailInfo = getCourseDetail(params);
        const getCurriculumCourseInfo = getCurriculumCourse({
          id: this.currNo,
        });
        // getCourseDetailInfo,
        Promise.all([getCurriculumCourseInfo])
          .then((res) => {
            if (res[0].errno === 0) {
              this.courseID = res[0].data.courseID
              // res[0].data = b;
              // this.taskSettings = res[1].data.taskSettings;
              // res[0].data.taskSettings = res[1].data.taskSettings;
              let currName = res[0].data.name;
              currName = currName.substring(
                0,
                currName.lastIndexOf("_") == -1
                  ? currName.length
                  : currName.lastIndexOf("_")
              );
              res[0].data.tutorStaffIconPath = res[0].data.iconPath;
              res[0].data.currName = currName;
              const currState = res[0].data.state
              Object.assign(res[0].data, res[0].data.courseData) //这样会把课程状态给替换掉了
              res[0].data.state = currState
              this.saveLocalStorageCourseInfo(res[0]);
              resolve(res[0]);
            } else {
              this.$antdMessage.error({
                content: "获取课程信息失败，请刷新页面！",
              });
            }
          })
          .catch((err) => {
            // this.$antdMessage.error({
            //   content: err,
            // });
          });
      });
    },

    // // 获取isGroupLeader
    // handleGetIsGroupLeader() {
    //   const params = {
    //     currNo: this.currNo
    //   }
    //   getMyChoose(params).then((res)=>{
    //     console.log(res);

    //   })
    // },

    async handleCourseDetailCreate() {
      // const courseId = this.courseID;
      const currNo = this.currNo;
      // 判断用户是否已选择课程
      let chooseInfo = false;
      // 当前课程Id在已发布课课程的编号
      // 如果roleFlag身份是学生 则获取已选课列表 等待已选课程数据返回
      if (this.userInfo.authNum && this.userInfo.authNum?.indexOf(1) !== -1) {
        // 移除我的课程列表的缓存
        await this.fetchChoosedCourses({ userID: this.userInfo.userID });
        chooseInfo = this.getChooseCourses.find((item) => {
          return item.currNo == currNo;
        });
        const result = await getSingleChooseInfo({ currNo })

        if (result.errno == 0) {
          const cInfo = result.data
          this.isGroupLeader = cInfo.isGroupLeader;
        }
      }

      // 如果已选课 获取课程信息和学习数据


      if (chooseInfo) {
        this.chooseNo = chooseInfo.chooseNo;

        if (chooseInfo.selectedTutorID) this.checkTeacher = chooseInfo.selectedTutorID
        if (chooseInfo.selectedTutorName) this.selectedTutorName = chooseInfo.selectedTutorName
        // 获取课程信息
        const fetchCoursesDetail = this.fetchLocalStorage();
        // 获取学习数据 getTaskResult
        const fetchCoursesData = this.fetchCoursesData({
          chooseNo: chooseInfo.chooseNo,
          currNo: Number(currNo),
          userID: this.userInfo.userID,
        });
        // 等待 课程信息和学习数据 的接口返回数据
        Promise.all([fetchCoursesDetail, fetchCoursesData])
          .then((res) => {
            if (res[1].errno === 0) {
              if (!this.successGetStudyData) return
              let guidelineResultsIsNull = false
              res[1].data.forEach(taskData => {
                if (!taskData.guidelineResults) guidelineResultsIsNull = true
              })
              // 补全引导文没有学习数据
              if (guidelineResultsIsNull) {
                this.setGuilinesDefaultStudyData(res[0].data, res[1].data)
              }
              this.courseInfo = res[0].data;
              this.myStudyData = res[1].data;
              this.setTagsViewTitle({ name: this.courseInfo.currName, currNo: this.currNo });
              // this.handleCheckAllTaskResult();
              // this.handleAddState();
            } else {
              this.handleCourseDetailCreate();
            }
          })
          .catch((err) => {
            // this.$antdMessage.error({
            //   content: err,
            // });
          });
      } else {
        // 获取课程信息
        this.fetchLocalStorage().then((res) => {
          this.courseInfo = res.data;
          this.setTagsViewTitle({ name: this.courseInfo.currName, currNo: this.currNo });
        });
      }
    },

    // 给学习数据的引导文添加默认数据
    setGuilinesDefaultStudyData(cData, studyData) {
      const taskGroupData = cData.courseData.taskGroups
      studyData.forEach(item => {
        if (!item.guidelineResults) {
          const guideline_taskGroupID = item.taskGroupID
          const guideline_taskID = item.taskID
          const cTaskData = taskGroupData[guideline_taskGroupID]?.tasks?.[guideline_taskID]
          const cGuidelines = cTaskData?.guidelines
          if (cGuidelines) {
            const cGuidelinesLength = Object.keys(cGuidelines).length
            item.guidelineResults = {}
            Object.keys(cGuidelines).forEach(key => {
              const guideline = cGuidelines[key]
              // 模拟数据格式
              if (guideline.operType !== '查阅' || cGuidelinesLength === 1) {
                item.guidelineResults[guideline.guidelineID] = getNewGuidelineStudyData(guideline);
              }
            })
          }
        }
      })
      let localMyStudyData = localStorage.getItem("studyData");
      let localObject = localMyStudyData && isJSONstr(localMyStudyData) ? JSON.parse(localMyStudyData) : {};
      localObject[this.currNo] = {};
      localObject[this.currNo][this.userInfo.userID] = studyData;
      localStorage.setItem("sData_eTime", new Date().getTime() + 60000);
      localStorage.setItem("studyData", JSON.stringify(localObject));
    },

    // 保存课程详情到本地
    saveLocalStorageCourseInfo(res) {
      res.data["saveTime"] = new Date().getTime();
      let locals_CourseInfo = JSON.parse(localStorage.getItem("courseInfo"));
      if (!locals_CourseInfo) locals_CourseInfo = [];
      locals_CourseInfo = locals_CourseInfo.filter(
        (item) => item.currNo !== res.data.currNo
      );
      locals_CourseInfo.push(res.data);
      localStorage.setItem("courseInfo", JSON.stringify(locals_CourseInfo));
    },

    // 获取课程学习数据
    fetchCoursesData(params) {
      return new Promise((resolve, reject) => {
        try {
          let localMyStudyData = localStorage.getItem("studyData");
          const mStudyData =
            localMyStudyData && isJSONstr(localMyStudyData)
              ? JSON.parse(localMyStudyData)
              : {};
          // 获取学习数据的过期时间
          let currTime = new Date().getTime();
          let sData_eTime = localStorage.getItem("sData_eTime") || currTime - 1;
          if (
            mStudyData[params.currNo]?.[this.userInfo.userID] &&
            currTime < sData_eTime
          ) {
            this.myStudyData = mStudyData[params.currNo]?.[this.userInfo.userID];
            resolve({ errno: 0, data: this.myStudyData });
            // resolve({ errno: 0, data: a });
          } else {
            getMyStudyData(params).then((res) => {
              this.myStudyData = res.data;
              res.data.forEach(item => {
                if (item.guidelineResults) {
                  Object.keys(item.guidelineResults)?.forEach(key => item.guidelineResults[key].guidelineID = Number(key))
                }
              })
              // this.myStudyData = a;
              let localObject = mStudyData;
              localObject[params.currNo] = {};
              localObject[params.currNo][this.userInfo.userID] = this.myStudyData;
              // // 引导文的学习数据需要存在才保存到缓存
              // if (!guidelineResultsIsNull) {
              // 学习数据过期时间1分钟
              localStorage.setItem("sData_eTime", new Date().getTime() + 60000);
              localStorage.setItem("studyData", JSON.stringify(localObject));
              // }
              this.successGetStudyData = true
              resolve(res);
            }).catch(err => {
              this.$antdMessage.error({
                content: "学习数据获取失败",
              });
              reject("学习数据获取失败！")
              this.successGetStudyData = false
              throw "获取学习数据接口异常"
            });
          }
        } catch (error) {
          this.successGetStudyData = false
          Notification({
            type: "error",
            title: "错误",
            message: "获取学习数据失败",
            duration: 0,
          })
          reject("学习数据获取失败")
        }
      });
    },

    // 添加课程
    async chooseCourse(tutorID) {
      // 判断用户是否登录
      // if (!this.$store.commit("user/checkUserIslogin", this)) return;
      if (!this.userInfo.accessToken) {
        this.$router.push({
          name: "Login",
        });
        return;
      }

      if (
        this.courseInfo.currNo === 6 &&
        this.courseInfo.courseID === 8 &&
        [225, 421].indexOf(this.userInfo.userID) == -1
      ) {
        return this.$antdMessage.error({
          content: "暂无权限！",
        });
      }

      // 判断课程选课时间
      const currTime = new Date().getTime()
      const openChooseTime = new Date(this.courseInfo.openChooseTime).getTime()
      const closeChooseTime = new Date(this.courseInfo.closeChooseTime).getTime()
      if (currTime < openChooseTime) {
        return this.$antdMessage.warning({ content: "操作失败，未到开始时间！" })
      }

      if (currTime > closeChooseTime) {
        return this.$antdMessage.warning({ content: "操作失败，已超过规定时间！" })
      }
      if (this.userInfo.authName.indexOf('教师') === -1 && this.userInfo.authNum.indexOf(2) === -1) {
        if (this.courseInfo.onlyInClassCanSelect && this.courseInfo.classIDList) {
          const classIDList = this.courseInfo.classIDList.split(',').map(item => Number(item))
          if (this.courseInfo.notForNormalClass) {
            if (this.userInfo.otherClassIDList) {
              const uOtherCList = this.userInfo.otherClassIDList.split(',').map(item => Number(item))
              uOtherCList.push(Number(this.userInfo.classID))
              if (classIDList?.length && !classIDList?.some(item => uOtherCList.includes(item))) {
                return this.$antdMessage.warning({ content: "未开通此班级的课程！" })
              }
            } else {
              return this.$antdMessage.warning({ content: "未绑定非常规班级！" })
            }
          } else {
            if (classIDList?.length && classIDList?.indexOf(this.userInfo.classID) == -1) {
              return this.$antdMessage.warning({ content: "未开通此班级的课程！" })
            }
          }
        }
      }
      // 判断用户是否只是学生
      // if (this.userInfo.roleFlag == 1) {
      //   if (!this.userInfo.realName ||!this.userInfo.classID ||!this.userInfo.email ||!this.userInfo.stuNum ||!this.userInfo.mPhone ||!this.userInfo.gender) {
      //     return this.$antdMessage.warning({content: "用户信息不完整，请在个人中心补全个人信息"})
      //   }
      // }

      const params = {
        courseID: Number(this.courseID),
        currNo: Number(this.currNo),
        userID: this.userInfo.userID,
        tutorID: tutorID || undefined
      };

      getChooseCreate(params).then((res) => {
        if (res.errno === 0) {
          this.$antdMessage.success({
            content: this.courseInfo.courseType !== '比赛' ? "选课成功" : "报名成功",
          });
          // 选课后重新获取选课列表 todo 异常
          Session.remove(`/api/choose/mylist?userID=${this.userInfo.userID}`)
          this.$store.dispatch("courses/getMyCourses", { that: this });
          this.chooseNo = res.data.chooseNo;
          const currNo = this.currNo;
          // 将学习数据缓存时间设为过期
          localStorage.setItem("sData_eTime", new Date().getTime() - 60000);
          // 等待获取学习数据
          this.handleCourseDetailCreate()
          // const fetchStudyData = this.fetchCoursesData({
          //   chooseNo: res.data.chooseNo,
          //   currNo: currNo,
          //   userID: this.userInfo.userID,
          // }).then((res) => {
          //   if (res.errno === 0) {
          //     // this.handleCheckAllTaskResult();
          //     // this.handleAddState();
          //   }
          // });
        } else if (!res.errno && res.errno !== 0) {
          this.$antdMessage.error({
            content: res,
          });
        } else {
          if (res.errno == 11003) {
            this.$antdMessage.error({
              content: this.courseInfo.courseType !== '比赛' ? res.message : "报名失败",
            });
          } else {
            this.$antdMessage.error({
              content: res.message,
            });
          }
        }
      });
    },
    // 修改指导教师
    chooseUpdate(tutorID) {
      const currTime = new Date().getTime()
      const closeChooseTime = new Date(this.courseInfo.closeChooseTime).getTime()

      if (currTime > closeChooseTime) {
        return this.$antdMessage.warning({ content: "操作失败，已超过规定时间！" })
      }

      const params = {
        courseID: Number(this.courseID),
        currNo: Number(this.currNo),
        userID: this.userInfo.userID,
        tutorID: tutorID,
        chooseNo: Number(this.chooseNo)
      };
      getChooseUpdateTutor(params).then(res => {
        if (res.errno == 0) {
          this.$antdMessage.success({
            content: '修改成功',
          });
          Session.remove(`/api/choose/mylist?userID=${this.userInfo.userID}`)
        } else {
          {
            this.$antdMessage.error({
              content: res.message,
            });
          }
        }
      })
    },
    // 继续学习
    continueLearn() {
      if (!this.lastLearn) return this.scrollIntoView(0);
      let group = this.lastLearn.split("-")[0];
      let task = this.lastLearn.split("-")[1];
      let guideline = this.lastLearn.split("-")[2];
      let groupCollaspe = this.$refs.rv.$children[0].$children[group - 1];
      let taskCollapse = groupCollaspe.$children[0].$children[task - 1];
      let guidelineCollapse = taskCollapse.$children[guideline - 1];
      if (!groupCollaspe.isActive) {
        this.$nextTick(() => {
          groupCollaspe.handleHeaderClick();
          if (!taskCollapse.isActive) {
            this.$nextTick(() => {
              taskCollapse.handleHeaderClick();
              if (!guidelineCollapse.answerRegion)
                guidelineCollapse.answerRegion = true;
            });
          } else {
            if (!guidelineCollapse.answerRegion)
              guidelineCollapse.answerRegion = true;
          }
        });
      } else {
        if (!taskCollapse.isActive) {
          this.$nextTick(() => {
            taskCollapse.handleHeaderClick();
            if (!guidelineCollapse.answerRegion)
              guidelineCollapse.answerRegion = true;
          });
        } else {
          if (!guidelineCollapse.answerRegion)
            guidelineCollapse.answerRegion = true;
        }
      }
      this.$nextTick(() =>
        this.scrollIntoView(Number(this.learnGroupIndex.split("-")[0]))
      );
    },

    // 课程详情页
    buy() {
      // 判断是否已登录。未登录则跳转登录页
      if (!this.userInfo.accessToken) {
        this.$antdMessage.warning("登陆后才能付款哦~");
        this.$router.push({
          name: "Login",
        });
        return;
      }

      this.$antdMessage.warning("付款功能暂未开放");
    },

    // 展开 collapse
    openCollapse(compoment) {
      this.$nextTick(() => compoment.handleHeaderClick());
    },
    // 任务学习情况回调
    handleChangeLSion(data) {
      this.speedOfProgress = data;
    },
    // 学习进度回调
    handleChangeProgress(data) {
      this.computedLearned = data;
    },

    // 获取提问列表
    fetchQuestionInfo() {
      getQuestionList({ currNo: this.currNo }).then((data) => {
        this.replyList = data.filter(item => item.currNo == this.currNo) || []
        // if (res.errno === 0) {
        //   this.replyList = res.data || []
        // }
      })
    },
    // 关闭选择教师窗口
    closeSelectTeacher() {
      this.visibleSelectTeacher = false
      // this.checkTeacher = ''
    },
    // 获取对应课程学生的基本选修数据
    fetchCurrNoData(params) {
      getCurrNoData_Stu(params).then((data) => {
        if (data) {
          this.tableData = data;
          this.handelSort("stuNum", true);
          // 浅拷贝数组 当原数组发生改变时 当前内存地址也会传递
        }
      });
    },
    // 排序 todo 有的时候顺序不一样
    handelSort(name, firstFormat) {
      if (this.sortName === name)
        return (this.sortName = ""), this.handelSort("stuNum", true);
      if (name === "realName") {
        this.tableData.sort(function (a, b) {
          return a[name]?.localeCompare(b[name]);
        });
      } else if (name == "finishedCount") {
        this.tableData
          .sort(function (a, b) {
            return (
              a[name] - b[name] ||
              a["studyingCount"] - b["studyingCount"] ||
              !(a["notStartCount"] - b["notStartCount"])
            );
          })
          .reverse();
      } else {
        this.tableData.sort((a, b) => {
          return a[name] - b[name];
        });
      }
      // debugger
      if (!firstFormat) this.sortName = name;
    },
    handleChangeShowProper() {
      if (!this.userInfo.accessToken) {
        this.$router.push({
          name: "Login",
        });
        return;
      }
    },
    // 打开链接
    openViewScore(isPersonal) {
      if (isPersonal) {
        window.open(`${location_QuestionBank(window)}/personal?userID=${this.userInfo.userID}&currNo=${this.currNo}`)
      } else
        window.open(`${location_QuestionBank(window)}/study/${this.currNo}`)
    }
  },
};
</script>

<style lang="stylus">
.courseDetail {
  .course-header {
    height: 200px;
    background: url('~@/assets/images/courseBg.png') no-repeat;
    background-repeat: no-repeat;
    background-size: 100% 100%;

    .header-content {
      position: relative;
      padding-top: 34px;
      margin: 0 auto;
      max-width: 1200px;

      .courseDesc {
        .courseName {
          margin-top: 12px;
          width: 100%;
          font-family: PMingLiU-ExtB;
          font-size: 32px;
          color: #ffffff;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        .descDetail {
          margin-top: 17px;
          display: flex;
          align-items: center;

          .teacher-detail {
            margin-right: 54px;
            display: flex;
            align-items: center;

            .picture {
              margin-right: 10px;
              width: 50px;
              height: 50px;
              background-color: rgba(117, 117, 117, 0.51);
              border-radius: 50%;
              overflow: hidden;

              img {
                width: 50px;
                height: 50px;
                object-fit: cover;
              }
            }

            .teacherDesc {
              .name {
                height: 19px;
                font-family: PMingLiU-ExtB;
                font-weight: bold;
                font-size: 14px;
                line-height: 20px;
                color: #ffffff;
              }

              .label {
                margin-top: 5px;
                width: 32px;
                height: 21px;
                text-align: center;
                font-family: PMingLiU-ExtB;
                font-size: 14px;
                line-height: 22px;
                color: #ffffff;
                background-color: #d99c36;
                border-radius: 5px;
              }
            }
          }

          .viewScore {
            span {
              cursor: pointer;
              font-weight: bold;
              background: #66b1ff;
              font-size: 20px;
              color: #fff;
              transition: .1s linear;
            }

            span:hover {
              color: blue
            }
            
          }

          .courseIntroduce {
            display: flex;
            font-family: PMingLiU-ExtB;
            font-size: 14px;
            color: #ffffff;

            div {
              position: relative;
              padding: 0 20px;
            }

            @media only screen and (min-width: 768px) and (max-width: 1024px) {
              div {
                position: relative;
                padding: 0 15px;
              }
            }

            div::after {
              position: absolute;
              content: '';
              top: 5px;
              right: 0;
              width: 1px;
              height: 10px;
              background: #fff;
            }

            div:last-child::after {
              content: none;
            }
          }
        }
      }

      .courseShare-box {
        position: absolute;
        top: 52px;
        right: 0;
      }
    }
  }

  .course-headerNav {
    height: 70px;
    line-height: 70px;
    background-color: #ffffff;
    box-shadow: 0px 8px 16px 0px rgba(7, 23, 39, 0.1);

    .headerNav-content {
      width: 100%;
      margin: 0 auto;
      max-width: 1200px;

      ul {
        padding: 0;
        margin: 0;
        list-style: none;
        display: flex;
        justify-content: flex-start;
        align-items: center;

        li {
          width: 50px;
          text-align: center;
          cursor: pointer;
          margin: 0 40px;
          position: relative;
          font-family: PMingLiU-ExtB;
          font-size: 16px;
          height: 70px;
          color: #003262;

          .liBadge {
            position: absolute;
            top: -13px;
            right: -13px;
            height: 0;
          }
        }

        li:first-child {
          margin-left: 0;
        }

        .li-active {
          font-weight: bold;
          color: #003262;
        }

        .li-active::after {
          position: absolute;
          content: '';
          left: 0;
          bottom: 18px;
          width: 12px;
          height: 2px;
          background: #003262;
          transform: translate(150%, 0);
        }
      }
    }
  }

  .course-main {
    position: relative;
    margin: 0 auto;
    max-width: 1200px;

    .finishSituation {
      position: absolute;
      left: 887px;
      top: calc(100vh - 70px - 200px - 70px);

      // position: fixed;
      // right: calc(((100vw - 755px) / 2));
      .situationIconBox {
        display: flex;
        align-items: center;
        cursor: pointer;
        margin-bottom: 20px;

        .IconBox {
          position: relative;
        }

        .IconBox::after {
          cursor: default;
          position: absolute;
          content: '';
          left: 50%;
          right: 50%;
          bottom: -30px;
          width: 3px;
          height: 20px;
          border-right: 3px dashed #bfbfbf;
          transform: translate(-80%, -50%);
        }

        .name {
          margin-left: 16px;
          font-family: PMingLiU-ExtB;
          font-size: 14px;
          color: #666666;
        }
      }

      .isFinish {
        .IconBox::after {
          border-color: #f6ad35;
        }
      }
    }

    .situationIconBox:last-child {
      .IconBox::after {
        content: none;
      }
    }

    .isSelected {
      top: 380px;
    }

    .mall-studyAndstudent {
      display: none;
    }

    .studyAndstudent {
      position: absolute;
      top: -250px;
      right: 0;

      .studyBox {
        padding: 21px 22px 30px;
        width: 320px;
        background-color: #ffffff;
        box-shadow: 0px 8px 16px 0px rgba(7, 23, 39, 0.1);
        border-radius: 20px;

        .selectedCourse {
          padding-bottom: 24px;

          .desc {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .percent {
              font-family: PMingLiU-ExtB;
              font-weight: bold;
              font-size: 16px;
              color: #000000;
            }

            .time {
              font-family: PMingLiU-ExtB;
              font-size: 12px;
              color: #666666;
            }
          }

          .progress {
            margin: 12px 0 18px;
          }

          .lastStudy, .speedOfProgress {
            font-family: PMingLiU-ExtB;
            font-size: 12px;
            color: #666666;
          }

        }
        
        .chooseTeacher {
          margin-bottom: 8px
          cursor: pointer;
          font-family: PMingLiU-ExtB;
          font-size: 14px;
          color: #666666;
          span:hover {
            color: #409EFF;
          }
        }
        .ischeckTeachered {
          display: flex;

          span {
            flex: 1;
            .startStudy {
              width: auto
            }
          }
          button {
            width: 100%;
          }
          
          .btn {
            flex: 1;
          }
        }

        .btn {
          cursor: pointer;
          outline: none;
          width: 275px;
          height: 45px;
          background-color: #f6ad35;
          border-radius: 30px;
          border: none;
          font-family: PMingLiU-ExtB;
          font-size: 16px;
          color: #ffffff;
        }

        .contentBox {
          margin-top: 16px;

          .content {
            margin-top: 35px;

            .title {
              margin-top: 13px;
              font-family: PMingLiU-ExtB;
              font-weight: bold;
              font-size: 14px;
              color: #000000;
            }

            .desc {
              margin-top: 9px;
              font-family: PMingLiU-ExtB;
              font-size: 10px;
              color: #535353;
            }
          }

          .content:first-child {
            margin-top: 0;
          }
        }
      }

      .learningStudents-ipad {
        display: none;
      }

      .learningStudents, .learningStudents-ipad {
        padding: 19px 17px 0;
        margin-top: 45px;
        width: 320px;
        height: 209px;
        background-color: #ffffff;
        box-shadow: 0px 8px 16px 0px rgba(7, 23, 39, 0.1);
        border-radius: 20px;

        .title {
          display: flex;
          align-items: center;
          justify-content: center;

          .name {
            position: relative;
            line-height: 1;
          }

          .name::after {
            position: absolute;
            content: '';
            bottom: -8px;
            width: 80px;
            height: 3px;
            background: #f6ad35;
            border-radius: 40px;
            transform: translate(-120%, 0);
          }

          .iconBox {
            margin-left: 4px;

            // width: 19px;
            // height: 18px;
            img {
              cursor: pointer;
              width: 100%;
            }
          }
        }

        .students {
          margin-top: 20px;
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;

          .pictureBox {
            margin-bottom: 18px;
            width: 49px;
            height: 50px;
            background-color: rgba(195, 195, 195, 0.68);
            border-radius: 50%;
            overflow: hidden;

            img {
              object-fit: cover;
              width: 100%;
              height: 100%;
            }
          }
        }
      }
    }

    .danmuComponent {
      z-index: 999;
      position: sticky;
      margin-top: 20px;
      float: right;
      top: 100px;
      right: 0;
      // width: 300px;
      text-align: right;
      height: 0;

      .danmuBox {
        width: 300px;
      }
      
      .vue-danmaku {
        transition: background 0.2s linear;

        .danmus {
          .dm {
            color: #fff
          }
        }
      }
    }

    // .danmuComponent:hover {
    //   .vue-danmaku {
    //     background: rgba(0, 0, 0, 0.05) !important;
    //   }
    // }
  }

  @media only screen and (min-width: 768px) and (max-width: 1024px) {
    .course-header {
      height: 200px;

      .header-content {
        padding: 29px 70px 0;

        .courseDesc {
          .courseName {
            margin: 0;
            font-family: PMingLiU-ExtB;
            font-size: 5vw;
            color: #ffffff;
          }

          .descDetail {
            margin-top: 2vw;

            .teacher-detail {
              margin-right: 15px;
            }
          }
        }
      }
    }

    .course-headerNav {
      position: relative;
      height: 290px;
      line-height: 60px;

      .headerNav-content {
        position: absolute;
        bottom: 0;
        box-shadow: 0vw 1vw 2vw 0vw rgba(7, 23, 39, 0.1);

        ul {
          padding: 0 70px 0;

          a {
            margin: 0 23px;
          }

          li {
            height: 60px;
            color: #003262;
          }
        }
      }
    }

    .course-main {
      padding-top: 2vw;
      min-height: 420px;

      .finishSituation {
        z-index: 999;
        position: fixed;
        top: 32vw;
        right: 6vw;
        left: unset;
        width: 24px;

        .situationIconBox {
          .name {
            display: none;
          }

          .IconBox::after {
            transform: translate(-45%, -50%);
          }
        }
      }

      .studyAndstudent {
        top: -302px;
        width: 100vw;
        display: flex;
        align-items: flex-start;
        justify-content: center;

        .studyBox {
          height: 27vw;

          .contentBox {
            height: 12vw;
            overflow: auto;
          }
        }

        .learningStudents-ipad {
          display: block;
          margin: 0;
          margin-left: 37px;
          width: 199px;
          height: 209px;

          .title {
            .name {
              font-size: 2vw;
            }

            .name::after {
              transform: translate(-138%, 0);
            }

            .iconBox {
              display: none;
            }

            .name::after {
              bottom: -1vw;
            }
          }
        }

        .learningStudents {
          display: none;
        }
      }
    }
  }

  @media only screen and (max-width: 767px) {
    .course-header {
      height: 41vw;

      .header-content {
        padding: 17vw 4vw 0;

        .courseDesc {
          .courseName {
            margin: 0;
            font-family: PMingLiU-ExtB;
            font-size: 5vw;
            color: #ffffff;
          }

          .descDetial {
            margin-top: 2vw;

            .teacher-detail {
              .teacherDesc {
                display: flex;
                align-items: center;

                .name {
                  margin-right: 3vw;
                }

                .label {
                  margin: 0;
                  width: 9vw;
                }
              }
            }
          }
        }
      }
    }

    .course-headerNav {
      height: 60px;
      line-height: 60px;

      .headerNav-content {
        ul {
          padding: 0 6vw 0 5vw;
          display: flex;
          justify-content: space-between;
          align-items: center;

          a {
            margin: 0;
          }

          li {
            margin: 0;
            height: 60px;
            color: #003262;
          }

          .li-active::after {
            font-size: 4vw;
            bottom: 4vw;
          }
        }
      }
    }

    .course-main {
      padding: 0 15px;

      .finishSituation {
        display: none;
      }

      .studyAndstudent {
        margin-top: 2vw;
        position: relative;
        top: unset;
        right: unset;

        .studyBox {
          margin: 0 auto;
        }

        .learningStudents {
          display: none;
        }

        .learningStudents-ipad {
          padding-top: 0;
          display: block;
          margin: 0 auto;
          margin-top: 4vw;
          width: 100%;
          height: 26vw;

          .students {
            .pictureBox {
              margin: 0;
            }
          }
        }
      }
    }
  }
}
.selectTeacher {
  .el-radio-group {
    display: flex;
    flex-flow: row;
    flex-wrap: wrap;
    width: 100%;
    // .el-radio {
    //   display: flex;
    //   align-items: center;
    //   .el-radio__label {
    //     display: flex;
    //     align-items: center;
    //     width: 100%;
    //   }
    // }
  }
  .teacherBox {
    padding: 5px;
    margin-right: 10px;
    margin-bottom: 10px;
    width: 190px;
    height: 235px;
    border: 1px solid #e3e5e7;
    border-radius: 5px;
    font-size: 14px

    .teacherInfo {
      margin-top: 10px;
    }

    .teacherName {
      margin-bottom: 5px;
      font-size: 16px
    }
    .imgBox {
      img {
        object-fit: contain;
        width: 180px;
        height: 85px;
      }
    }

    .teacherDesc {
      margin-bottom: 5px;
      max-width: 230px;
      height: 71px
      white-space: break-spaces;
      word-break: break-all;
      display: -webkit-box;
      -webkit-line-clamp: 4;
      -webkit-box-orient: vertical;
      line-height: 18px;
      overflow: hidden;
    }
  }
  .isSelectTeacher {
    border-color: #409EFF
  }
}

.teacherDescToolTip {
  max-width: 350px;
}
</style>